import React, {useState} from 'react';
import "./index.css"
import { Modal, Button } from "antd";
import { connect } from "react-redux";
import { bindActionCreators } from "redux"
import { actions } from "./store"
import TodoModal from '../../components/todoModal/TodoModal';

 function TodoList({todoLists, isModalVisible, showModal, deteleAction, upAction, downAction}) {
     const [updataItem, setUpdataItem] = useState(null)

    function showModal_1() {
        showModal()  // 显示 和 隐藏 弹框组件
        setUpdataItem({updata: false})
    }

    function todoUpdata(item, index) {  // 更新操作
        setUpdataItem({...item, updata: true, index})
        showModal({...item, index: index})
    }


    function todoDetele(item, index) {
        // console.log("删除", index)
        deteleAction(index)
    }

    function up(item, index) {
        // console.log("上移")
        upAction({...item, index})
    }
    function down(item, index) {
        // console.log("下移")
        downAction({...item, index})
    }

    function renderTodoList() {
        if(todoLists.length == 0) return <div> 数据出错 </div>
        return todoLists.map((item, index) => <li key={item.id} > 
            <div>
                <div> {item.name} </div>
                <div> {item.age} </div>
                <div> {item.address} </div>
            </div>
            <div>
                <div className='button'>
                    { index !== 0 && <button onClick={() => {up(item, index)}} >上移</button> }
                    { (todoLists.length-1) !== index && <button onClick={() => {down(item, index)}}>下移</button>}
                </div>
                <div>
                    <button onClick={() => {todoUpdata(item, index)}} >更新</button>
                    <button onClick={() => {todoDetele(item, index)}} >删除</button>
                </div>
            </div>
          </li> )
    }
  return (
    <div>
        
        <Button type="primary" onClick={showModal_1}>添加</Button>

        <TodoModal isModalVisible={isModalVisible} updataItem={updataItem} />
       

        <ul>
            {renderTodoList()}
        </ul>
    </div>
  )
}

export default connect(
    (state) => {
        return state.todoListStore
    }, 
    (dispatch) => {
        return bindActionCreators(actions, dispatch)
    }
)(TodoList)